package com.example.cs4.service.impl;

import com.example.cs4.mapper.ChatHistoryMapper;
import com.example.cs4.model.ChatHistory;
import com.example.cs4.service.ChatHistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class ChatHistoryServiceImpl implements ChatHistoryService {

    @Autowired
    private ChatHistoryMapper chatHistoryMapper;

    // 获取所有公共历史消息
    @Override
    public List<ChatHistory> getAllChatHistory() {
        if (chatHistoryMapper == null){
            throw new RuntimeException("公共历史消息不能为空");
        }
        return chatHistoryMapper.selectAll();
    }

    // 获取与指定用户相关的消息历史（包括公共消息和私聊消息）
    @Override
    public List<ChatHistory> getChatHistoryForUser(String username) {
        if (username == null){
            throw new IllegalArgumentException("用户名不能为空");
        }
        return chatHistoryMapper.selectByUser(username);
    }

    // 获取与指定接收者或发送者相关的消息历史
    @Override
    public List<ChatHistory> getChatHistoryByReceiverOrSender(String receiver, String sender) {
        if (receiver == null && sender == null){
            throw new IllegalArgumentException("接收者和发送者不能为空");
        }
        return chatHistoryMapper.findByReceiverOrSender(receiver, sender);
    }

    // 保存聊天历史
    @Override
    public void saveChatHistory(ChatHistory chatHistory) {
        if (chatHistory == null){
            throw new IllegalArgumentException("聊天历史不能为空");
        }
        if (chatHistory.getMessage() == null){
            throw new IllegalArgumentException("聊天消息不能为空");
        }
        if (chatHistory.getSender() == null){
            throw new IllegalArgumentException("发送者不能为空");
        }
        if (chatHistory.getReceiver() == null) {
            throw new IllegalArgumentException("接收者不能为空");
        }
        chatHistoryMapper.insert(chatHistory);
    }

    @Override
    public int getUnreadMessageCount(String username) {
        if (username == null) {
            throw new IllegalArgumentException("用户名不能为空");
        }
        return chatHistoryMapper.countUnreadMessages(username);
    }

    // 新增方法：根据消息ID列表标记消息为已读
    @Override
    public void markMessagesAsReadByIds(List<Integer> messageIds) {
        chatHistoryMapper.markMessagesAsReadByIds(messageIds);
    }
}